<?php
class AppController extends Controller {
	var $helpers = array('Html','Form','Session','Time','Text',"Link","Ajax");
	var $components = array('Acl','Uploader.Uploader','RequestHandler','Session','Cookie','Auth');
	var $uses = array('Header','User','News','Infor','Intro','Support','Slide','Cateproduct','Cateservice','Catediscover','Guest','Product');
   function beforeFilter(){
		parent::beforeFilter();
    $locale = Configure::read('Config.language');
    $this->Auth->loginAction = array('admin' => true, 'controller' => 'users', 'action' => 'login');
    $this->Auth->loginRedirect = array('admin' =>true,'controller' => 'pages', 'action' => 'display');
    $this->Auth->loginError = 'Thông tin đăng nhập không đúng';
    $this->Auth->authError = 'Truy cập bị từ chối';
    $this->Auth->allow('admin_login','index','display','catenews','detail','view','search','login','home','chitiet');
		//debug($this->params);
		//if($this->_checkLanguage())
           // $this->redirect($this->referer(), null, true);

		if(isset($this->params['admin'])) {
			$this->layout = 'admin';
			if($this->Auth->user()) $this->set('ssid',$this->Auth->user());
			$this->_admin();
		}else{
            $this->_setLanguage();
			$this->layout = 'default';
      if(isset($this->params['language'])){
        $this->lg =  $this->params['language'];
      }else $this->lg =  Configure::read('Config.language');
			/*
			$locale = Configure::read('Config.language');
			if ($locale && file_exists(VIEWS . $locale . DS . $this->viewPath)) {
				$this->viewPath = $locale . DS . $this->viewPath;
			}
			*/
      $lang = $this->Session->read('Config.language');
			$this->_site();
      $this->set('lang',$lang);
		}
    $this->set('model',$this->uses[0]);

	}

    private function _setLanguage() {
      //if the cookie was previously set, and Config.language has not been set
      //write the Config.language with the value from the Cookie
          if ($this->Cookie->read('lang') && !$this->Session->check('Config.language')) {
              $this->Session->write('Config.language', $this->Cookie->read('lang'));
          }
         //if the user clicked the language URL
          else if (   isset($this->params['language']) &&
          ($this->params['language'] !=  $this->Session->read('Config.language'))
                 ) {
              //then update the value in Session and the one in Cookie
              $this->Session->write('Config.language', $this->params['language']);
              $this->Cookie->write('lang', $this->params['language'], false, '20 days');
          }
      }

      //override redirect
      public function redirect( $url, $status = NULL, $exit = true ) {
          if (!isset($url['language']) && $this->Session->check('Config.language')) {
              $url['language'] = $this->Session->read('Config.language');
          }
          parent::redirect($url,$status,$exit);
      }


	function _site(){
    $hSlide = $this->Slide->find('all');
    $hService = $this->Cateservice->find('all',array('conditions'=>array('status'=>2,'lang'=>$this->lg),"limit"=>60));

    $menu_products = $this->Cateproduct->find('list', array('conditions'=>array('status'=>2,'lang'=>$this->lg),'order'=>array('Cateproduct.order'=>'asc')));
		$hed = $this->Header->find('first', array('conditions'=>array('status'=>2),'order'=>array('id'=>'desc')));
		$menu_quangchau = $this->Catediscover->find('list', array('conditions'=>array('status'=>2,'lang'=>$this->lg),'order'=>array('Catediscover.order'=>'asc')));
    $menu_services = $this->Cateservice->find('list', array('conditions'=>array('status'=>2,'lang'=>$this->lg),'order'=>array('Cateservice.order'=>'asc')));
    $menu_intros = $this->Intro->find('all', array('conditions'=>array('status'=>2,'lang'=>$this->lg),'order'=>array('Intro.order'=>'asc')));
    $menu_support = $this->Support->find('all', array('conditions'=>array('status'=>2)));
    //$sContact = $this->Infor->find('first', array('conditions'=>array('lang'=>$this->lg,'area'=>'contact'),'order'=>array('Infor.id'=>'DESC')));
    $sTuyendung = $this->News->find('all', array('conditions'=>array('status'=>2,'catenews_id'=>2,'lang'=>$this->lg),'order'=>array('News.id'=>'DESC'),'limit'=>3));
    $sIntro = $this->Infor->find('first', array('conditions'=>array('status'=>2,'lang'=>$this->lg,'area'=>'about'),'order'=>array('Infor.id'=>'DESC')));
    $sFooter = $this->Infor->find('first', array('conditions'=>array('status'=>2,'lang'=>$this->lg,'area'=>'footer'),'order'=>array('Infor.id'=>'DESC')));
		$sSlogan = $this->Infor->find('first', array('conditions'=>array('status'=>2,'lang'=>$this->lg,'area'=>'slogan'),'order'=>array('Infor.id'=>'DESC')));
		$this->set(compact('hed','sTuyendung','hSlide','sSlogan','hService','menu_products','menu_quangchau','menu_services','menu_intros','menu_support','sContact','sIntro','sFooter'));
	}
	function _admin(){
		$idus=NULL;
		if($this->Auth->user()){
              $idus = $this->Auth->user('id');
          }
		$newsadmin = $this->News->find('list',array('limit'=>5,'order News.id'=>' DESC'));
		$inforlogin  = $this->News->query("SELECT * FROM lastlogin WHERE users_id = '".$idus."' limit 0,1");
		$product = $this->Product->find('list',array('fields'=>array('id','name'),'limit'=>5,'order Product.id'=>' DESC'));
		$this->set(compact('newsadmin','inforlogin','product'));
	}


/*
function _checkLanguage()
    {
        if(!$this->Session->check('Config.language') || $this->name == "Switchto")
        {
            $supported_lang = Configure::read('LANGUAGE.supported');
            $default_lang   = Configure::read('LANGUAGE.default');
            $lang = null;
            if($this->name == "Switchto")
                $lang = $this->action;

            // we need the Cookie

            App::Import('Component', 'Cookie');
            $cookie = & new CookieComponent;
            $cookie->domain = '';
            $cookie->name   = 'MYAPP';
            $cookie->time   = '+360 days';
            $cookie->key    = 'whatever-key-you-wish';
            $cookie->startup();

            // and L10n object
            if(!class_exists("L10n"))
                uses('l10n');

            $l10n = & new L10n();

            if(!$lang || !in_array($lang, $supported_lang))
            {
                if($cookie->read('tutolanguage.lang') )
                {
                    $lang = $cookie->read('tutolang/lang');
                    if(!in_array($lang, $supported_lang))
                        $lang = null;
                }
                // try to find a language from browser that we support
                if(!$lang)
                {
                    $browserLang = split ('[,;]', env('HTTP_ACCEPT_LANGUAGE'));
                    foreach($browserLang as $langKey )
                    {
                        if(isset($l10n->__l10nCatalog[$langKey]) &&
                                in_array($l10n->__l10nCatalog[$langKey]['locale'], $supported_lang) )
                        {
                            $lang = $l10n->__l10nCatalog[$langKey]['locale'];
                            break;
                        }
                    }
                }
            }

            // still no language, get first supported

            if(!$lang)
                $lang = $language_default;

            // set the language, and write in cookie

            $l10n->__setLanguage($lang);
            $cookie->write(array('tutolanguage.lang' => $lang));
            $this->Session->write('Config.language',$lang);
            if($this->name == "Switchto")
                return true;
        }

        return false;
    }
    */

}
function liststatus(){
	return array(1=>'Không hiển thị',2=>'Hiển thị');
}
function getlang($str='vie'){
    switch ($str) {
        case 'eng': $s = "Tiếng Anh"; break;
        case 'chi': $s = "Tiếng Trung"; break;
        default: $s = "Tiếng Việt";break;
    }
    return $s;
}
function search($array, $key, $value)
	{
		$results = array();

		if (is_array($array))
		{
			if (isset($array[$key]) && $array[$key] == $value)
				$results[] = $array;

			foreach ($array as $subarray)
				$results = array_merge($results, search($subarray, $key, $value));
		}

		return $results;
	}
  function countuser(){
    $tid = 36288000;
    $file = "./files/cou6nter.txt";
    if(!isset($_COOKIE["count"])) {
      if(file_exists($file)) {
        $fil = fopen($file, "r");
        $count = fread($fil, 8);
        fclose($fil);
      }
      else {
        $count=0;
      }
      $count++;
      $fil = fopen($file, "w");
      fwrite($fil, $count);
      fclose($fil);
      setcookie("count","yes",time()+$tid);
    }
  }
?>